﻿using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace OCR
{
    public partial class History : Form
    {
        //全局结果数据集合
        private List<HistoryInfo> historys;
        public History()
        {
            InitializeComponent();
            this.dataGridView2.AutoGenerateColumns = false;
        }

        private void History_Load(object sender, EventArgs e)
        {
            //判断有没有全局结果数据
            if (File.Exists(OCR.HistoryFilePath))
            {
                string str = File.ReadAllText(OCR.HistoryFilePath);
                historys = JsonConvert.DeserializeObject<List<HistoryInfo>>(str);
            }
            else
            {
                historys = new List<HistoryInfo>();
            }
            historys.Sort(delegate(HistoryInfo a, HistoryInfo b) { return b.Date.CompareTo(a.Date); });

            this.dataGridView2.DataSource = historys;
        }


        /// <summary>
        /// 表格单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0)
                {
                    //打开图片目录
                    if (e.ColumnIndex == 2)
                    {

                        Process.Start(this.dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

                    }
                    else if (e.ColumnIndex == 3)//导出excel
                    {
                        HistoryInfo history = historys[e.RowIndex];
                        this.saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
                        if (this.saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            string resultPath = this.saveFileDialog1.FileName;
                            HSSFWorkbook workbook = new HSSFWorkbook();

                            // 工作簿 
                            ISheet sheet = workbook.CreateSheet("识别结果");
                            // 工作表 
                            IRow row = sheet.CreateRow(0);
                            row.CreateCell(0).SetCellValue("运营商");
                            row.CreateCell(1).SetCellValue("面值");
                            row.CreateCell(2).SetCellValue("截止期");
                            row.CreateCell(3).SetCellValue("卡号图片");
                            row.CreateCell(4).SetCellValue("卡号");
                            row.CreateCell(5).SetCellValue("密码图片");
                            row.CreateCell(6).SetCellValue("密码");
                            row.CreateCell(7).SetCellValue("图片文件名");

                            int rowIndex = 1;
                            foreach (var info in history.Results)
                            {
                                IRow rowTmp = sheet.CreateRow(rowIndex);
                                rowTmp.CreateCell(0).SetCellValue(history.OcrConfig.FactoryName);
                                rowTmp.CreateCell(1).SetCellValue(history.OcrConfig.FaceValue);
                                rowTmp.CreateCell(2).SetCellValue(history.OcrConfig.ValidDate);
                                byte[] bytes = System.IO.File.ReadAllBytes(Path.Combine(history.ImageFolder, info.ImageName + "_NO.jpg"));
                                int pictureIdx = workbook.AddPicture(bytes, PictureType.JPEG);
                                HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                                // 插图片的位置  HSSFClientAnchor（dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
                                HSSFClientAnchor anchor = new HSSFClientAnchor(70, 10, 0, 0, 3, rowIndex, 4, rowIndex + 1);
                                //把图片插到相应的位置
                                HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);

                                rowTmp.CreateCell(4).SetCellValue(info.NoValue);
                                byte[] bytes1 = System.IO.File.ReadAllBytes(Path.Combine(history.ImageFolder, info.ImageName + "_PW.jpg"));
                                int pictureIdx1 = workbook.AddPicture(bytes1, PictureType.JPEG);
                                HSSFPatriarch patriarch1 = (HSSFPatriarch)sheet.CreateDrawingPatriarch();
                                // 插图片的位置  HSSFClientAnchor（dx1,dy1,dx2,dy2,col1,row1,col2,row2) 后面再作解释
                                HSSFClientAnchor anchor1 = new HSSFClientAnchor(70, 10, 0, 0, 5, rowIndex, 6, rowIndex + 1);
                                //把图片插到相应的位置
                                HSSFPicture pict1 = (HSSFPicture)patriarch.CreatePicture(anchor1, pictureIdx1);

                                rowTmp.CreateCell(6).SetCellValue(info.PwValue);
                                rowTmp.CreateCell(7).SetCellValue(info.ImageName + ".jpg");
                                rowIndex++;
                            }

                            using (Stream stream = File.OpenWrite(resultPath))
                            {
                                workbook.Write(stream);
                            }
                            MessageBox.Show("已经存到文件，路径" + resultPath);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source);
            }

        }

        private void btDel_Click(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("确认删除选择的记录？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    foreach (DataGridViewRow row in this.dataGridView2.SelectedRows)
                    {
                        HistoryInfo result = historys[row.Index];
                        DirectoryInfo dr = new DirectoryInfo(result.ImageFolder);
                        if (Directory.Exists(result.ImageFolder))
                        {
                            Directory.Delete(result.ImageFolder, true);
                        }

                        historys.RemoveAt(row.Index);
                    }
                    string str1 = JsonConvert.SerializeObject(historys);
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(OCR.HistoryFilePath, false))
                    {
                        file.WriteLine(str1);
                    }
                    this.dataGridView2.DataSource = null;
                    this.dataGridView2.DataSource = historys;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
           
        }
    }
}

